package cn.tedu.pdfamily.product.service.impl;

import cn.tedu.pdfamily.product.exception.ServiceException;
import cn.tedu.pdfamily.product.mapper.UserMapper;
import cn.tedu.pdfamily.product.mapper.UserRoleMapper;
import cn.tedu.pdfamily.product.pojo.dto.UserAddNewDTO;
import cn.tedu.pdfamily.product.pojo.dto.UserLoginDTO;
import cn.tedu.pdfamily.product.pojo.dto.UserUpdateDTO;
import cn.tedu.pdfamily.product.pojo.entity.User;
import cn.tedu.pdfamily.product.pojo.entity.UserRole;
import cn.tedu.pdfamily.product.pojo.vo.UserListItemVO;
import cn.tedu.pdfamily.product.pojo.vo.UserStandardVO;
import cn.tedu.pdfamily.product.security.UserDetail;
import cn.tedu.pdfamily.product.service.IUserService;
import cn.tedu.pdfamily.product.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 处理用户数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {


    @Value("${pdfamily.jwt.secret-key}")
    private String secretKey;
    @Value("${pdfamily.jwt.duration-in-minute}")
    private long durationInMinute;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public String login(UserLoginDTO userLoginDTO) {
        log.debug("开始处理【用户登录】的业务，参数：{}",userLoginDTO);
        // 执行认证
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(), userLoginDTO.getPassword());
        Authentication authenticateResult = authenticationManager.authenticate(authentication);
        log.debug("认证通过,认证管理器返回:{}",authenticateResult);

        //从认证结果中获取所需的数据,将用于生成JWT
        Object principal = authenticateResult.getPrincipal();
        log.debug("认证结果中的当事人类型:{}",principal.getClass().getName());
        UserDetail userDetail = (UserDetail) principal;
        String username = userDetail.getUsername();
        Long id = userDetail.getId();
        Collection<GrantedAuthority> authorities = userDetail.getAuthorities();
        String authoritiesJsonString = JSON.toJSONString(authorities);

        // 生成JWT数据时,需要填充装到JWT中的数据
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",id);
        claims.put("username",username);
        claims.put("authoritiesJsonString",authoritiesJsonString);
        log.debug("向JWT中存入id:{}",id);
        log.debug("向JWT中存入username:{}",username);
        log.debug("向JWT中存入authoritiesJsonString:{}",authoritiesJsonString);
        // 以下是生成JWT的固定代码
        Date date = new Date(System.currentTimeMillis() + durationInMinute * 60 * 1000L);
        String jwt = Jwts.builder()
                // Header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // Payload
                .setClaims(claims)
                // Signature
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
        log.debug("生成的JWT：{}", jwt);
        return jwt;
    }

    @Override
    public void addNew(UserAddNewDTO userAddNewDTO) {
        log.debug("开始处理【添加用户】的业务，参数：{}", userAddNewDTO);

        log.debug("即将检查用户名是否被占用……");
        {
            // 从参数对象中获取username
            String username = userAddNewDTO.getUsername();
            // 调用userMapper的countByUsername()方法执行统计查询
            int count = userMapper.countByUsername(username);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加用户失败，用户名【" + username + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将检查手机号码是否被占用……");
        {
            // 从参数对象中获取手机号码
            String phone = userAddNewDTO.getPhone();
            // 调用userMapper的countByPhone()方法执行统计查询
            int count = userMapper.countByPhone(phone);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加用户失败，手机号码【" + phone + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将检查手机号码是否被占用……");
        {
            // 从参数对象中获取手机号码
            String phone = userAddNewDTO.getPhone();
            // 调用userMapper的countByPhone()方法执行统计查询
            int count = userMapper.countByPhone(phone);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加用户失败，手机号码【" + phone + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将检查电子邮箱是否被占用……");
        {
            // 从参数对象中获取电子邮箱
            String email = userAddNewDTO.getEmail();
            // 调用userMapper的countByEmail()方法执行统计查询
            int count = userMapper.countByEmail(email);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加用户失败，电子邮箱【" + email + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        //创建User对象
        User user = new User();
        // 通过BeanUtils.copyProperties()方法将参数对象的各属性值复制到User对象中
        BeanUtils.copyProperties(userAddNewDTO, user);
        // 取出密码，进行加密处理，并将密文封装回User对象中
        String rawPassword = user.getPassword();
        String encodePassword = passwordEncoder.encode(rawPassword);
        user.setPassword(encodePassword);
        // 补全User对象中的属性值: loginCount >>> 0
        user.setLoginCount(0);
        // 调用userMapper的insert()方法插入数据
        log.debug("即将插入用户数据，参数：{}", user);
        int rows = userMapper.insert(user);
        // 判断插入数据的结果是否符合预期
        if (rows != 1) {
            String message = "添加用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 插入用户与角色关联的数据
        Long[] roleIds = userAddNewDTO.getRoleIds();
        UserRole[] userRoles = new UserRole[roleIds.length];
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < roleIds.length; i++) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleIds[i]);
            userRole.setGmtCreate(now);
            userRole.setGmtModified(now);
            userRoles[i] = userRole;
        }
        rows = userRoleMapper.insertBatch(Arrays.asList(userRoles));
        if (rows != roleIds.length) {
            String message = "添加用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除用户】的业务，参数：{}", id);
        // id值为1的用户不允许被删除
        if (id == 1) {
            // 是：抛出异常（ERR_NOT_FOUND）
            String message = "删除用户失败，尝试删除的用户数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 调用userMapper的UserStandardVO getStandardById(Long id)方法执行查询
        UserStandardVO queryResult = userMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：抛出异常（ERR_NOT_FOUND）
            String message = "删除用户失败，尝试删除的用户数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 调用userMapper的int deleteById(Long id)执行删除，并获取返回的行数
        int rows = userMapper.deleteById(id);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }

        // 删除用户与角色的关联数据
        rows = userRoleMapper.deleteByUserId(id);
        if (rows < 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除用户失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void setEnable(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void updateInfoById(Long id, UserUpdateDTO userUpdateDTO) {
        // 检查尝试访问的数据是否存在
        UserStandardVO queryResult = userMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        userMapper.update(user);
    }

    private void updateEnableById(Long id, Integer enable) {
        String[] tips = {"禁用", "启用"};
        log.debug("开始处理【{}用户】的业务，参数：{}", tips[enable], id);

        // 判断参数id是否为1
        if (id == 1) {
            String message = tips[enable] + "用户失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查尝试访问的数据是否存在
        UserStandardVO queryResult = userMapper.getStandardById(id);
        if (queryResult == null) {
            String message = tips[enable] + "用户失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断状态是否冲突（当前已经是目标状态）
        if (queryResult.getEnable().equals(enable)) {
            String message = tips[enable] + "用户失败，用户账号已经处于" + tips[enable] + "状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 准备执行更新
        User user = new User();
        user.setId(id);
        user.setEnable(enable);
        int rows = userMapper.update(user);
        if (rows != 1) {
            String message = tips[enable] + "用户失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        
    }

    @Override
    public void setDisable(Long id) {
        updateEnableById(id, 0);
    }

    @Override
    public List<UserListItemVO> list() {
        log.debug("开始处理【查询用户列表】的业务，无参数");
        List<UserListItemVO> list = userMapper.list();
        Iterator<UserListItemVO> iterator = list.iterator();
        while (iterator.hasNext()) {
            UserListItemVO item = iterator.next();
            if (item.getId() == 1) {
                iterator.remove();
                break;
            }
        }
        return list;
    }

    @Override
    public UserStandardVO getUserById(Long id) {
        log.debug("开始处理【查询用户列表】的业务，无参数");
        UserStandardVO standardById = userMapper.getStandardById(id);
        if(standardById==null){
            String message = "当前资源不存在";
            throw new ServiceException(ServiceCode.ERR_SELECT,message);
        }
        return standardById;
    }
}
